import random
from datetime import date, timedelta, datetime, time

import aiomysql

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, field_validator

from apps.utils.sql_conn import get_db_cursor

interface = APIRouter()


class RegisterRequest(BaseModel):
    email: str
    department: str
    day: date
    timestate: str
    doctor: str

    @field_validator("day")
    def check_day(cls, v):
        today = date.today()
        if v < today or v > today + timedelta(days=7):
            raise ValueError("日期必须在今日起7天内")
        return v

    @field_validator("timestate")
    def check_timestate(cls, v):
        if v not in ["1", "2", "3"]:
            raise ValueError("时间段必须为1，2，3")
        return v


@interface.get("/interface/features", response_description="获取所有特点数据")
async def get_features():
    async with get_db_cursor() as cursor:
        try:
            await cursor.execute(
                "SELECT id, feature FROM feature"
            )
            features_data = await cursor.fetchall()

            if features_data:
                result = []
                for idx, feature in enumerate(features_data, start=1):
                    feature_info = {
                        f"特点{idx}": {
                            "id": feature["id"],
                            "name": feature["feature"],
                        }
                    }
                    result.append(feature_info)
                return result
            else:
                return {"message": "未找到任何特点数据"}

        except aiomysql.Error as e:
            error_code = e.args[0]
            error_msg = e.args[1]
            detail = f"数据库查询失败：{error_msg} (错误代码: {error_code})"
            raise HTTPException(
                status_code=500,
                detail=detail
            )


@interface.get("/interface/Bigfeature", response_description="获取所有大特点数据")
async def get_features():
    async with get_db_cursor() as cursor:
        try:
            await cursor.execute(
                "SELECT id, title, Bigfeature FROM Bigfeature"
            )
            features_data = await cursor.fetchall()

            if features_data:
                result = []
                for idx, Bigfeature in enumerate(features_data, start=1):
                    feature_info = {
                        f"特点{idx}": {
                            "id": Bigfeature["id"],
                            "Title": Bigfeature["title"],
                            "Bigfeature": Bigfeature["Bigfeature"]
                        }
                    }
                    result.append(feature_info)
                return result
            else:
                return {"message": "未找到任何特点数据"}

        except aiomysql.Error as e:
            error_code = e.args[0]
            error_msg = e.args[1]
            detail = f"数据库查询失败：{error_msg} (错误代码: {error_code})"
            raise HTTPException(
                status_code=500,
                detail=detail
            )


@interface.post("/interface/guahao", response_description="挂号预约")
async def register_guahao(
        req: RegisterRequest, ):
    async with get_db_cursor() as cursor:
        try:
            await cursor.execute(
                "SELECT realname, identitycard FROM user_info WHERE email = %s",
                (req.email,)
            )
            user_data = await cursor.fetchone()
            if not user_data:
                raise HTTPException(status_code=404, detail="未找到用户")
            realname = user_data["realname"]
            identitycard = user_data["identitycard"]

            await cursor.execute(
                """
            SELECT id FROM guahao
            WHERE idcard = %s AND day = %s AND department = %s AND timestate = %s
            """,
                (identitycard, req.day, req.department, req.timestate)
            )
            if await cursor.fetchone():
                raise HTTPException(status_code=400, detail="不可重复预约")

            random_minutes = random.randint(3, 8)

            if req.timestate == "1":
                start_time, end_time = time(8, 0), time(12, 0)
            elif req.timestate == "2":
                start_time, end_time = time(13, 30), time(17, 30)
            else:  # timestate == "3"
                start_time, end_time = time(18, 0), time(20, 0)

            start_dt = datetime.combine(req.day, start_time)
            end_dt = datetime.combine(req.day, end_time)

            await cursor.execute("""
            SELECT timefinish FROM guahao
            WHERE day = %s AND department = %s AND timestate = %s
            ORDER BY id DESC LIMIT 1
        """, (req.day, req.department, req.timestate))
            last_record = await cursor.fetchone()
            last_finish = last_record["timefinish"] if last_record else None

            today = date.today()
            if req.day == today:
                now = datetime.now()
                if last_finish:
                    new_start = last_finish
                else:
                    if now < start_dt:
                        new_start = start_dt
                    elif now <= end_dt:
                        new_start = now
                    else:
                        raise HTTPException(status_code=400, detail="该时间段已结束")
            else:
                new_start = start_dt if not last_finish else last_finish

            new_finish = new_start + timedelta(minutes=random_minutes)
            if new_finish > end_dt:
                raise HTTPException(status_code=400, detail="该时间段挂号已满")

            sql = """
            INSERT INTO guahao 
            (people, idcard, department, day, timestate, doctor, timefinish) 
            VALUES (%s, %s, %s, %s, %s, %s, %s)
        """
            await cursor.execute(sql, (
                realname, identitycard, req.department, req.day,
                req.timestate, req.doctor, new_finish
            ))
            return {
                "status": "success",
                "data": {
                    "姓名": realname,
                    "预约日期": req.day.strftime("%Y-%m-%d"),
                    "时间段": f"时段{req.timestate}",
                    "结束时间": new_finish.strftime("%Y-%m-%d %H:%M:%S"),
                    "科室": req.department,
                    "医生": req.doctor,
                    "预计时长": f"{random_minutes}分钟"
                }
            }

        except aiomysql.IntegrityError as e:
            raise HTTPException(status_code=400, detail=f"数据库错误: {str(e)}")
        except HTTPException:
            raise
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"操作失败: {str(e)}")


@interface.get("/interface/banfirst", response_description="禁用挂号接口1")
def banfirst():
    today = date.today()
    twelve_oclock = datetime.combine(today, datetime.min.time().replace(hour=12, minute=0, second=0))
    return {"current_date_12h": twelve_oclock.strftime("%Y-%m-%d %H:%M:%S")}


@interface.get("/interface/bansecond", response_description="禁用挂号接口2")
def bansecond():
    today = date.today()
    twelve_oclock = datetime.combine(today, datetime.min.time().replace(hour=17, minute=30, second=0))
    return {"current_date_12h": twelve_oclock.strftime("%Y-%m-%d %H:%M:%S")}


@interface.get("/interface/banthird", response_description="禁用挂号接口3")
def banthird():
    today = date.today()
    twelve_oclock = datetime.combine(today, datetime.min.time().replace(hour=22, minute=00, second=0))
    return {"current_date_12h": twelve_oclock.strftime("%Y-%m-%d %H:%M:%S")}


@interface.get("/interface/queue_status", response_description="获取各科室当前排队详情")
async def get_queue_status():
    async with get_db_cursor() as cursor:
        try:
            # 获取当前时间
            now = datetime.now()
            today = date.today()

            # 更新已完成的挂号记录状态
            await cursor.execute("""
                UPDATE guahao 
                SET success = 'success' 
                WHERE day = %s AND timefinish < %s 
            """, (today, now))

            # 查询今天未完成的挂号记录
            await cursor.execute("""
                SELECT id, people, department 
                FROM guahao 
                WHERE day = %s 
                AND success IS  NULL
                ORDER BY department, id
            """, (today,))

            records = await cursor.fetchall()

            # 按科室分组并封装结果
            result = {}
            for record in records:
                dept = record["department"]
                if dept not in result:
                    result[dept] = []

                result[dept].append({
                    "id": len(result[dept]) + 1,
                    "人名": record["people"]
                })

            # 转换为列表形式，每个科室为一个字典
            final_result = [{"科室": dept, "排队人员": people_list}
                            for dept, people_list in result.items()]

            return {"科室排队详情": final_result}

        except aiomysql.Error as e:
            error_code = e.args[0]
            error_msg = e.args[1]
            detail = f"数据库查询失败：{error_msg} (错误代码: {error_code})"
            raise HTTPException(
                status_code=500,
                detail=detail
            )
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"操作失败: {str(e)}")


@interface.get("/interface/my_records", response_description="查询个人所有就诊记录")
async def get_my_records(email: str):
    async with get_db_cursor() as cursor:
        try:
            await cursor.execute(
                "SELECT realname FROM user_info WHERE email = %s",
                (email,)
            )
            user_data = await cursor.fetchone()
            if not user_data:
                raise HTTPException(status_code=404, detail="未找到该用户")
            realname = user_data["realname"]

            await cursor.execute(
                """
                SELECT id,people, idcard, department, day, timestate, 
                       doctor, success, timefinish 
                FROM guahao 
                WHERE people = %s
                """,
                (realname,)
            )
            records = await cursor.fetchall()

            result = []
            for record in records:
                success_status = "已完成就诊" if record["success"] is not None else "未就诊"
                formatted_record = {
                    "id": record["id"],
                    "people": record["people"],
                    "idcard": record["idcard"],
                    "department": record["department"],
                    "day": record["day"].strftime("%Y-%m-%d") if record["day"] else None,
                    "timestate": record["timestate"],
                    "doctor": record["doctor"],
                    "success": success_status,
                    "timefinish": record["timefinish"].strftime("%Y-%m-%d %H:%M:%S")
                    if record["timefinish"] else None
                }
                result.append(formatted_record)

            return {"个人就诊记录": result}

        except aiomysql.Error as e:
            error_code = e.args[0]
            error_msg = e.args[1]
            detail = f"数据库查询失败：{error_msg} (错误代码: {error_code})"
            raise HTTPException(status_code=500, detail=detail)
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"操作失败: {str(e)}")
